package cn.boodqian.airdata;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.*;

import com.google.appengine.api.utils.SystemProperty;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class AirdataServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		
		AirData data = new AirData();
		Map map = req.getParameterMap();
		if(map.containsKey("city") && map.containsKey("hour") && map.containsKey("location") && map.containsKey("ver")) {
			String city = req.getParameter("city");
			int hour = Integer.parseInt(req.getParameter("hour"));
			int location = Integer.parseInt(req.getParameter("location"));
			int ver = Integer.parseInt(req.getParameter("ver"));
			
			int appVer = Integer.parseInt(SystemProperty.applicationVersion.get().split("\\.")[0]);
			if(ver < appVer)
				hour = AirData.MAX_HOURS;
			
			if(city.compareTo("sh")==0) {
				AirDataProvider provider = null;
				if(location != 0) {
					if(location == 999) location = 0;
					provider = new ShanghaiAirDataProvider();
				} else {
					provider = new ShanghaiUSAirDataProvider();
				}
				data = provider.getAirData(location, hour);
				data.version = appVer;
			}
		}
		
		Gson gson = new Gson();
		String ret = gson.toJson(data);
		resp.getWriter().println(ret);
	}
}
